package com.hangwei.paperless;

import android.Manifest;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.hangwei.paperless.adapter.HorizontalPicAdapter;
import com.hangwei.paperless.adapter.sub.SubProcessListAdapter;
import com.hangwei.paperless.adapter.sub.SubProcessListStepAdapter;
import com.hangwei.paperless.model.bean.CardToSeal;
import com.hangwei.paperless.model.bean.ProcessSheet;
import com.hangwei.paperless.model.bean.SubProcessListAll;
import com.hangwei.paperless.model.bean.SubProcessListInfo;
import com.hangwei.paperless.presenter.StaticPresenter;
import com.hangwei.paperless.utils.JsonPostUtil;
import com.hangwei.paperless.utils.NFCCallBack;
import com.hangwei.paperless.widget.CardSealPop;
import com.twelve.all.base.NFCApp;
import com.twelve.all.net.CallBack;
import com.twelve.all.nfc.BasicActivity;
import com.twelve.all.nfc.Constants;
import com.twelve.all.nfc.MCReader;
import com.twelve.all.nfc.PreferencesUtil;
import com.twelve.all.nfc.Utils;
import com.twelve.all.utils.LoadingDialog;
import com.twelve.all.utils.LogUtil;
import com.twelve.all.utils.SPKey;
import com.twelve.all.utils.SPUtil;
import com.twelve.all.utils.ToastUtil;
import com.twelve.all.utils.Tools;

import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 衬套加工单单独界面
 */
public class ProcessActivity extends BasicActivity {
    private SubProcessListAdapter mAdapter;
    private String mUserId;
    private RecyclerView mRecyclerView;

    private NFCCallBack mNFCCallBack;
    private CardSealPop mCardSealPop;
    private boolean mCanCard;

    private SubProcessListStepAdapter mStepAdapter;
    private TextView mTvManualNo;
    private TextView mTvBushPN;
    private TextView mTvBushIPLNo;
    private TextView mTvMaterial;
    private TextView mTvQty;
    private TextView mTvDes;
    private HorizontalPicAdapter mPicAdapter;

    private String mSubBillId;
    private TextView mTvJobNo;
    private TextView mTvSheetNo;
    private ProcessSheet mInfo;
    private String stepId;
    private List<String> mPicList;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_process);
        findViewById(R.id.back).setOnClickListener(v -> finish());
        mInfo = (ProcessSheet) getIntent().getSerializableExtra("info");
        mUserId = SPUtil.getString(SPKey.Account.USER_ID);
        mRecyclerView = findViewById(R.id.recyclerView);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new SubProcessListAdapter(null,1) {
            @Override
            protected void seal(final SubProcessListInfo item, final List<SubProcessListInfo> data) {
                sealByCard(item.id, new NFCCallBack() {
                    @Override
                    public void onCallBack(List<CardToSeal.StampBean> stampIds, String userId) {
                        if (stampIds == null || stampIds.size() == 0) {
                            ToastUtil.showCenterToast("无印章！");
                        } else {
                            final LoadingDialog loadingDialog = new LoadingDialog(ProcessActivity.this);
                            loadingDialog.show();
                            String jsonData = JsonPostUtil.buildProcessList(mUserId, data, item, stampIds.get(0).stampId, userId);
                            RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), jsonData);
                            StaticPresenter.stampBushingSheetDRS(requestBody, new CallBack<Object>() {
                                @Override
                                public void onCompleted(Object o) {
                                    loadingDialog.dismiss();
                                    initData();
//                                    mMainBottomPopupWindow.dismiss();
                                }

                                @Override
                                public void onError() {
                                    loadingDialog.dismiss();
                                }
                            });
                        }
                    }
                });
            }
        };
        mRecyclerView.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.tvSave) {
                    SubProcessListAll.DrsListBean bean = mAdapter.getData().get(position);
                    final LoadingDialog loadingDialog = new LoadingDialog(ProcessActivity.this);
                    loadingDialog.show();
                    StaticPresenter.saveBushingSN(mUserId, mSubBillId, bean.billSeq, bean.bushingSN, new CallBack<Object>() {
                        @Override
                        public void onCompleted(Object o) {
                            loadingDialog.dismiss();
                            ToastUtil.showCenterToast("保存成功！");
//                            initData();
                        }

                        @Override
                        public void onError() {
                            loadingDialog.dismiss();
                            ToastUtil.showCenterToast("保存失败！");
                        }
                    });
                }
            }
        });
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.addHeaderView(getHeader());
        mAdapter.addFooterView(getFooter());
        initData();
    }


    private void initData() {
        final LoadingDialog loadingDialog = new LoadingDialog(this);
        loadingDialog.show();
        StaticPresenter.getBushingSheets(mUserId, mInfo.billId, mInfo.subBillId, null, new CallBack<SubProcessListAll>() {
            @Override
            public void onCompleted(SubProcessListAll subProcessListAll) {
                loadingDialog.dismiss();
                mPicList = subProcessListAll.picList;
                mAdapter.setNewData(subProcessListAll.drsList);
//                mActivity.setStepId(subProcessListAll.id);
                if (subProcessListAll.stepList != null && subProcessListAll.stepList.size() > 0) {
                    for (int i = 0; i < subProcessListAll.stepList.size(); i++) {
                        SubProcessListAll.StepListBean bean = subProcessListAll.stepList.get(i);
                        if (TextUtils.isEmpty(bean.technicianId)) {
                            bean.canSeal = true;
                            break;
                        }
                    }
                }
                mPicAdapter.setNewData(subProcessListAll.picList);
                mStepAdapter.setNewData(subProcessListAll.stepList);
                mSubBillId = subProcessListAll.subBillId;
                mTvManualNo.setText(Tools.checkedString(subProcessListAll.manualNo));
                mTvBushPN.setText(Tools.checkedString(subProcessListAll.bushPN));
                mTvBushIPLNo.setText(Tools.checkedString(subProcessListAll.bushIPLNo));
                mTvMaterial.setText(Tools.checkedString(subProcessListAll.material));
                mTvQty.setText(Tools.checkedString(subProcessListAll.qty));
                String source = Tools.checkedString(subProcessListAll.description);
                String all = source.replaceAll("<p>", "<p  style=\"display:block;margin:0 0;\">");
                Spanned html;
                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N)
                    html = Html.fromHtml(all, Html.FROM_HTML_MODE_COMPACT);
                else html = Html.fromHtml(all);
                mTvDes.setText(html);
                mTvJobNo.setText(Tools.checkedString(subProcessListAll.woNo));
                mTvSheetNo.setText(Tools.checkedString(subProcessListAll.sheetNo));
                mRecyclerView.scrollToPosition(0);
            }

            @Override
            public void onError() {
                loadingDialog.dismiss();
            }
        });
    }

    private View getHeader() {
        View inflate = LayoutInflater.from(this).inflate(R.layout.header_sub_process_list, null);
        mTvJobNo = inflate.findViewById(R.id.tvJobNo);
        mTvSheetNo = inflate.findViewById(R.id.tvSheetNo);
        mTvManualNo = inflate.findViewById(R.id.tvManualNo);
        mTvBushPN = inflate.findViewById(R.id.tvBushPN);
        mTvBushIPLNo = inflate.findViewById(R.id.tvBushIPLNo);
        mTvMaterial = inflate.findViewById(R.id.tvMaterial);
        mTvQty = inflate.findViewById(R.id.tvQty);
        mTvDes = inflate.findViewById(R.id.tvDes);
        return inflate;
    }

    private View getFooter() {
        View inflate = LayoutInflater.from(this).inflate(R.layout.footer_sub_process_list, null);
        RecyclerView recyclerViewStep = inflate.findViewById(R.id.recyclerViewStep);
        recyclerViewStep.setLayoutManager(new LinearLayoutManager(this));
        mStepAdapter = new SubProcessListStepAdapter(null) {
            @Override
            protected void seal(final String id) {
                sealByCard(id, new NFCCallBack() {
                    @Override
                    public void onCallBack(List<CardToSeal.StampBean> stampIds, String userId) {
                        if (stampIds == null || stampIds.size() == 0) {
                            ToastUtil.showCenterToast("无印章！");
                        } else {
                            final LoadingDialog loadingDialog = new LoadingDialog(ProcessActivity.this);
                            loadingDialog.show();
                            StaticPresenter.stampBushingSheetStep(mUserId, id, userId, stampIds.get(0).stampId, new CallBack<Object>() {
                                @Override
                                public void onCompleted(Object o) {
                                    loadingDialog.dismiss();
                                    initData();
                                }

                                @Override
                                public void onError() {
                                    loadingDialog.dismiss();
                                }
                            });
                        }
                    }
                });
            }
        };
        recyclerViewStep.setAdapter(mStepAdapter);

        RecyclerView recyclerViewPic = inflate.findViewById(R.id.recyclerViewPic);
        LinearLayoutManager layout = new LinearLayoutManager(this);
        layout.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerViewPic.setLayoutManager(layout);
        mPicAdapter = new HorizontalPicAdapter(mPicList);
        recyclerViewPic.setAdapter(mPicAdapter);
        recyclerViewPic.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.sdv)
                    showBigPic((ArrayList<String>) mPicAdapter.getData(), position);
            }
        });
        return inflate;
    }

    @Override
    public void onNewIntent(Intent intent) {
        if (mCanCard && NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
            Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            tag = MCReader.patchTag(tag);
//            setTag(tag);
//            Utils.logUid(Utils.byte2Hex(tag.getId()));

            boolean isCopyUID = PreferencesUtil.getPreferences().getBoolean(
                    Constants.AutoCopyUID, false);
            if (isCopyUID) {
                int format = PreferencesUtil.getPreferences().getInt(
                        Constants.UIDFormat, 0);
                String fmtUID = Utils.byte2FmtString(tag.getId(), format);
            } else {
                // Show Toast message with UID.
                String msg = Utils.byte2Hex(tag.getId());
                LogUtil.i(msg);
                LoadingDialog loadingDialog = new LoadingDialog(this);
                loadingDialog.show();
                String userId = SPUtil.getString(SPKey.Account.USER_ID);
                StaticPresenter.getUserByCardId(userId, mInfo.billId, stepId, msg, new CallBack<CardToSeal>() {
                    @Override
                    public void onCompleted(CardToSeal cardToSeal) {
                        loadingDialog.dismiss();
                        if (mNFCCallBack != null)
                            mNFCCallBack.onCallBack(cardToSeal.stamp, cardToSeal.userId);
                        if (mCardSealPop != null && mCardSealPop.isShowing())
                            mCardSealPop.dismiss();
                    }

                    @Override
                    public void onError() {
                        loadingDialog.dismiss();
                        if (mCardSealPop != null && mCardSealPop.isShowing())
                            mCardSealPop.dismiss();
                        ToastUtil.showCenterToast("获取印章失败！");
                    }
                });


            }
//            return Utils.checkMifareClassicSupport(tag, context);
        }
    }

    public void sealByCard(String id, NFCCallBack NFCCallBack) {
        if (NFCApp.hasWritePermissionToExternalStorage(this)) {
            NFCApp.setUseAsEditorOnly(NFCApp.useAsEditorOnly());
            runStartUpNode(StartUpNode.FirstUseDialog);

                stepId = id;
            mNFCCallBack = NFCCallBack;
            if (mCardSealPop == null)
                mCardSealPop = new CardSealPop(this) {
                    @Override
                    protected void onDismiss1() {
                        mCanCard = false;
                    }
                };
            if (!mCardSealPop.isShowing())
                mCardSealPop.show();
//                mCardSealPop.showAtLocation(getWindow().getDecorView(), Gravity.CENTER, 0, 0);
            mCanCard = true;
        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
                    1);
        }
    }
    public void showBigPic(ArrayList<String> data, int position) {
        Intent intent = new Intent(this, BigPicActivity.class);
        intent.putExtra("list", data);
        intent.putExtra("position", position);
        startActivity(intent);
    }
}
